package cn.broadin.app.hotel;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tencent.mmkv.MMKV;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.broadin.app.hotel.app.AppConfig;
import cn.broadin.app.hotel.app.AppContext;
import cn.broadin.app.hotel.component.BaseView;
import cn.broadin.app.hotel.component.CardView;
import cn.broadin.app.hotel.component.CardViewData;
import cn.broadin.app.hotel.component.ComponentFacotry;
import cn.broadin.app.hotel.component.DefaultDataService;
import cn.broadin.app.hotel.component.LiveView;
import cn.broadin.app.hotel.component.LiveViewData;
import cn.broadin.app.hotel.component.TimePickerView;
import cn.broadin.app.hotel.component.TimePickerViewData;
import cn.broadin.app.hotel.config.WiFiAPService;
import cn.broadin.app.hotel.config.WifiHotUtil;
import cn.broadin.app.hotel.service.ListenNetStateService;
import cn.broadin.app.hotel.task.AdvDownloadTask;
import cn.broadin.app.hotel.util.MacAddressHelper;
import cn.broadin.app.hotel.util.UtilFile;
import cn.broadin.app.hotel.util.XHttpProxy;
import cn.broadin.app.hotel.util.XLog;
import cn.broadin.app.hotel.util.XToast;
import cn.broadin.app.hotel.util.XUIHelper;
import cn.broadin.app.hotel.util.XUtils;
import cn.broadin.app.hotel.view.EffectNoDrawBridge;
import cn.broadin.app.hotel.view.MainUpView;

public class HomeActivity extends BaseActivity{

    private static final  String KEY = "KEY_PORTAL";

    private Integer id;
    private String name;
    private String backgroud;
    // portal数据版本号
    private String portalVersion;

    private List<BaseView> views;

    private RelativeLayout rootLayout;
    private RelativeLayout rootLayout2;

    private MainUpView focusView;

    private static final int MSG_INIT_PORTAL_DATA_VIEW = 1;
    private static final int MSG_UPDATE_PORTAL_DATA_VIEW = 2;

    public static String hotelsIntroUrl;  //Web 应用入口
    public static String ProjectName;   //Web项目名称
    public  String macNum = "";
    public static final String NTP_SERVER = "ntp_server";
    private String Hotname = "";
    private String Hotpassword = "";
    private String auto_openFlag = "";
    private String HotStatus = "";
    boolean getConfigFlag = false;
    private WifiHotUtil wifiHotUtil;
    private String oldMarqueeText = "";
    public String productInfo = null;
    public String chipsInfo = null;
    private String authResult = "true";
    private String saveDirPath = "";
    public static String startVideoUrl;  //开机视频广告
    public static String portalUrl;     //portal跳转地址
    public static String marqueeText = "暂无提示信息";
    public static String indexVideoUrl;
    public static String indexVideoFile = null;

    private TextView marqueeTextView;

    // 网络图标
    private ImageView netWorkImageView;

    /**
     * 网络连接标志
     */
    private boolean networkFlag = false;

    /**
     * 房间数据是否已经初始化
     */
    private RoomInitStatus roomInfoInitFlag = RoomInitStatus.UNDO;

    private NetworkStatusReceiver networkReceiver;

    private View mOldFocus; // 4.3以下版本需要自己保存.

    public static final String NET_CHANGED_ACTION = "com.pd.NET_CHANGED_ACTION";
    public static final String FIRE_HAPPEN_ACTION = "com.pd.FIRE_HAPPEN_ACTION";
    public static final String FIRE_OVER_ACTION = "com.pd.FIRE_OVER_ACTION";


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
                case MSG_INIT_PORTAL_DATA_VIEW:
                    initPortalView((List<BaseView>) msg.obj);
                    break;
                case MSG_UPDATE_PORTAL_DATA_VIEW:
                    initPortalView((List<BaseView>) msg.obj);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);
        // 初始化数据
        rootLayout = findViewById(R.id.home_container);
        rootLayout2 = findViewById(R.id.home_container1);
        // 设置焦点
        focusView = findViewById(R.id.focus_view);
        // 网络图标
        netWorkImageView = findViewById(R.id.network);
        // 建议使用 NoDraw.
        focusView.setEffectBridge(new EffectNoDrawBridge());
        EffectNoDrawBridge bridget = (EffectNoDrawBridge) focusView.getEffectBridge();
        bridget.setTranDurAnimTime(200);
        // 设置移动边框的图片.
        focusView.setUpRectResource(R.drawable.focus);
        // 移动方框缩小的距离.
        focusView.setDrawUpRectPadding(new Rect(24, 24, 24, 24));
        // 焦点变化焦点切换
        rootLayout.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(View oldFocus, View newFocus) {
                if (newFocus != null)
                    newFocus.bringToFront(); // 防止放大的view被压在下面. (建议使用MainLayout)
                float scale = 1.0f;
                focusView.setFocusView(newFocus, mOldFocus, scale);
                mOldFocus = newFocus; // 4.3以下需要自己保存.
            }
        });
        // 初始化业务逻辑
        initView();
        // 初始化portal数据
        initPortalData();

        // 初始化room房间数据
        networkFlag = XUtils.isNetworkAvailable(this);
        if(networkFlag){
            initUpdateInfo.start();
            initRoomInfo();

        } else {
            // UI界面显示网络连接错误
            netWorkImageView.setImageResource(R.drawable.network1);
//			marqueeTextView.setText("请检查网络");
        }

        //设置热点
        if ( Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            String HotSpotconfigDir = "/data/local/Hotconfig/";
            String HotSpotconfigFile = "Hotspot.txt";
            File HotSpotfile = new File(HotSpotconfigDir,HotSpotconfigFile);
            if(HotSpotfile.exists() && HotSpotfile.length() != 0) {
                getHotspotConfig(HotSpotconfigDir,HotSpotconfigFile);
            }
        }

        // 注册广播
        registerBroadcastReceiver();

        // 启动网络监听服务
        Intent networkIntent = new Intent(this, ListenNetStateService.class);
        startService(networkIntent);

        if(getConfigFlag) {
            XLog.d("dyh : stb HotspotConfig-start");
            HotspotConfig.start();
        }
    }

    /**
     * 初始化数据
     */
    private void initView(){
        AppContext appContext = AppContext.getInstance();
        productInfo = appContext.getProductInfo();
        chipsInfo = appContext.getChipsInfo();
        portalUrl = appContext.getHotelsIntroUrl();
        indexVideoUrl = appContext.getIndexVideoUrl();
        if(productInfo == null || productInfo.equals("")) {  //再获取一次厂家信息
            productInfo = XUtils.getSystemInfo();
        }
        if(chipsInfo == null || chipsInfo.equals("")) {  //再获取一次厂家信息
            chipsInfo = XUtils.getChipsInfo();
        }

        authResult = appContext.getAuthFlag();
        if(authResult == null || authResult.equals("")) {
            authResult = "true";
        }

        WiFiAPService.startService(this);
        wifiHotUtil = new WifiHotUtil(this);

        //初始化相关参数
        macNum = MacAddressHelper.getInstance().getMacAddress(this);
        startVideoUrl = appContext.getStartVideoUrl();
        getIndexVideoPath();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("dyh---:","HomeActivity.onResume");
        initRoomInfo();
        if(views != null && !views.isEmpty()){
            for(BaseView view : views){
                view.onResume();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("dyh---:","MainActivity.onPause");
        roomInfoInitFlag = RoomInitStatus.UNDO;
        if(views != null && !views.isEmpty()){
            for(BaseView view : views){
                view.onPause();
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            int keyCode = event.getKeyCode();
            switch(keyCode){
                case KeyEvent.KEYCODE_F2:
                    openSys();
                    break;
                case KeyEvent.KEYCODE_0:
                    Intent mIntent = new Intent();
                    ComponentName comp = new ComponentName( "com.pd.apkinstaller", "com.pd.apkinstaller.MainActivity");
                    mIntent.setComponent(comp);
                    mIntent.setAction("android.intent.action.MAIN");
                    mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Bundle mbundle = new Bundle();
                    mbundle.putString("update_url", "http://172.19.4.240:8088/files/ottftp/7.zip");
                    mbundle.putString("productInfo", "JIUZHOU");
                    mIntent.putExtras(mbundle);
                    startActivity(mIntent);
                    break;
                case KeyEvent.KEYCODE_1:
                    XUIHelper.openInitActivity(HomeActivity.this);
                    break;
                case KeyEvent.KEYCODE_8:
                    Hotspot();
                    break;
                case KeyEvent.KEYCODE_9:
                    Intent intent = new Intent(this, ShowUiVersionActivity.class);
                    intent.putExtra("versionCode", AppConfig.versionCode);
                    intent.putExtra("versionDate", AppConfig.versionDate);
                    intent.putExtra("versionArea", AppConfig.versionArea);
                    startActivity(intent);
                    break;
                case KeyEvent.KEYCODE_BACK:
                case KeyEvent.KEYCODE_MENU:
                case KeyEvent.KEYCODE_HOME:
                    return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    public static String stbStateUrlFormat(Context mContext){
        String macNum = MacAddressHelper.getInstance().getMacAddress(mContext);
        String tempCode = AppConfig.secuCode + macNum + AppConfig.versionCode;
        String signCode = XUtils.md5(tempCode);
        XLog.d("tempCode: " + tempCode + ", signCode: " + signCode);

        String pingTempCode = AppConfig.secuCode + macNum;
        String pingsignCode = XUtils.md5(pingTempCode);
        String stbStateUrl = AppConfig.stbStateUrl + macNum + "&sign=" + pingsignCode;
        return stbStateUrl;
    }

    private void openSys() {
		/*try {
			Intent mIntent = new Intent();
			//ComponentName comp = new ComponentName("com.mbx.settingsmbox", "com.mbx.settingsmbox.SettingsMboxActivity");  //S805方案系统设置
			ComponentName comp = new ComponentName("com.tianci.setting","com.tianci.setting.activity.MainActivity");  //九州方案系统设置
			mIntent.setComponent(comp);
			mIntent.setAction("android.intent.action.MAIN");
			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(mIntent);
		} catch (Exception e) {
			e.printStackTrace();
			XToast.makeText(this, "应用启动失败！").show();
		}	*/
        XUIHelper.openPasswordActivity(HomeActivity.this);
    }

    private void Hotspot() {
        Intent intent = new Intent();
        intent.setClass(HomeActivity.this,HotsportConfig.class);
        startActivity(intent);
    }

    /**
     * 注册广播消息
     *
     * @author   long
     * @return void
     * @exception
     * @author   long
     * @since 1.0.0
     * @date 2016年1月4日 下午4:46:27
     */
    private void registerBroadcastReceiver() {
        networkReceiver = new NetworkStatusReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(NET_CHANGED_ACTION);
        filter.addAction(FIRE_HAPPEN_ACTION);
        filter.addAction(FIRE_OVER_ACTION);
        registerReceiver(networkReceiver, filter);
    }

    public class NetworkStatusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            XLog.e("broadcastReceiver--->action:" + action);
            if (MainActivity.NET_CHANGED_ACTION.equals(action)) {
                Bundle bundle = intent.getExtras();
                boolean flag = bundle.getBoolean("flag", false);
                XLog.d("broadcastReceiver--->network change status:" + flag);
                refreshNetworkStatus(flag);
            } else if(MainActivity.FIRE_HAPPEN_ACTION.equals(action)){
                // 火警
                XUIHelper.openFireActivity(HomeActivity.this);

            } else if(MainActivity.FIRE_OVER_ACTION.equals(action)){
                // 解除火警
                FireActivity.fireOver();
            }
        }
    }

    private void refreshNetworkStatus(boolean flag) {
        XLog.d("refreshNetworkStatus = " + flag);
        if(flag){
            networkFlag = true;
            netWorkImageView.setImageResource(R.drawable.network);
            // 网络恢复，刷新数据

            initRoomInfo();
        } else {
            networkFlag = false;
            netWorkImageView.setImageResource(R.drawable.network1);
            marqueeTextView.setText("请检查网络");

            // wifi掉线之后，需要重新加载数据
            roomInfoInitFlag = RoomInitStatus.UNDO;
        }
    }

    Thread initUpdateInfo = new Thread(new Runnable(){

        @Override
        public void run() {
            // TODO 自动生成的方法存根
            XLog.d("initUpdateInfo: start");
            String tempCode = AppConfig.secuCode + macNum + AppConfig.versionCode;
            String signCode = XUtils.md5(tempCode);
            XLog.d("product = "+productInfo+"tempCode: " + tempCode + ", signCode: " + signCode + ", macNum = " + macNum + "updateapiUrl = " + AppConfig.updateapiUrl + ",chips = " + chipsInfo);
            RequestParams requestParams = new RequestParams();
            requestParams.addBodyParameter("macaddr", macNum);
            requestParams.addBodyParameter("ver", AppConfig.versionCode);
            requestParams.addBodyParameter("product", productInfo);
            requestParams.addBodyParameter("chips", chipsInfo);
            requestParams.addBodyParameter("sign", signCode);
            HttpUtils httpUtils = XHttpProxy.getHttpUtils();

            httpUtils.send(HttpRequest.HttpMethod.POST, AppConfig.updateapiUrl, requestParams, new RequestCallBack<String>() {
                @Override
                public void onFailure(HttpException e, String msg) {
                    e.printStackTrace();
                    XToast.makeText(HomeActivity.this, "系统繁忙，请稍后再试！").show();
                }

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    XLog.i("initUpdateInfo.result: " + responseInfo.result);
                    JSONObject jsonObject = JSON.parseObject(responseInfo.result);
                    parseUpdateNum(jsonObject);
                }
            });
        }
    });

    private void parseUpdateNum(JSONObject jsonObject){
        try{
            String otaUpadateFlag = jsonObject.getString("upgrade");	// ota系统升级标志
            String update_url = jsonObject.getString("upgrade_url");	// ota系统升级地址
            otaUpdateOnline(otaUpadateFlag, update_url);
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    private void otaUpdateOnline(String flag, String url) {
        XLog.d("otaUpdateOnline flag = "+flag+",,,url =  " + url);
        //XToast.makeText(MainActivity.this, url).show();
        if(flag.equals("true")) {
            //先删除掉旧的升级包
            if(deleteFile()) {
                Intent mIntent = new Intent();
                ComponentName comp = new ComponentName( "com.pd.apkinstaller", "com.pd.apkinstaller.MainActivity");
                mIntent.setComponent(comp);
                mIntent.setAction("android.intent.action.MAIN");
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Bundle mbundle = new Bundle();
                mbundle.putString("update_url", url);
                mbundle.putString("productInfo", productInfo);
                mIntent.putExtras(mbundle);
                startActivity(mIntent);
            }else {
                XToast.makeText(HomeActivity.this, "升级失败,请重启机顶盒").show();
            }
        }
    }

    private Boolean deleteFile() {
        Boolean Flag = true;
        File f = new File(AppConfig.OtaFilePath);
        File[] fl = f.listFiles();

        for (int i=0; i<fl.length; i++) {
            if(fl[i].toString().endsWith(".zip") || fl[i].toString().endsWith(".ZIP"))
            {
                if(fl[i].delete())
                {
                    Flag = true;
                }else{
                    Flag = false;
                }
            }
        }
        return Flag;
    }

    /**
     * 初始化加载酒店房间详细信息
     *
     * @author   long
     * @return void
     * @exception
     * @author   long
     * @since 1.0.0
     * @date 2016年1月4日 下午4:22:17
     */
    private void initRoomInfo(){
        if(roomInfoInitFlag == RoomInitStatus.LOADING || roomInfoInitFlag == RoomInitStatus.DONE){
            return;
        }
        roomInfoInitFlag = RoomInitStatus.LOADING;
        String macNum = MacAddressHelper.getInstance().getMacAddress(this);
        String tempCode = AppConfig.secuCode + macNum + AppConfig.versionCode;
        String signCode = XUtils.md5(tempCode);
        XLog.d("tempCode: " + tempCode + ", signCode: " + signCode);
        RequestParams requestParams = new RequestParams();
        requestParams.addBodyParameter("macaddr", macNum);
        requestParams.addBodyParameter("ver", AppConfig.versionCode);
        requestParams.addBodyParameter("sign", signCode);
        HttpUtils httpUtils = XHttpProxy.getHttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.POST, AppConfig.roomUrl, requestParams, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException e, String msg) {
                roomInfoInitFlag = RoomInitStatus.UNDO;
                e.printStackTrace();
//				XToast.makeText(MainActivity.this, "系统繁忙，请稍后再试！").show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                XLog.i("responseInfo.result: " + responseInfo.result);
                JSONObject jsonObject = JSON.parseObject(responseInfo.result);
                parseRoomNum(jsonObject);
                roomInfoInitFlag = RoomInitStatus.DONE;
            }
        });
    }



    /**
     * 解析系统参数
     *
     * @author   long
     * @param jsonObject
     * @return void
     * @exception
     * @author   long
     * @since 1.0.0
     * @date 2016年1月4日 下午4:06:37
     */
    private void parseRoomNum(JSONObject jsonObject){
        try{
            //indexVideoUrl = jsonObject.getString("vad_url");		    // 首页左上角视频广告播放地址
            String advUrl = jsonObject.getString("ad_url");				// 广告图片链接地址
            String authFlag = jsonObject.getString("msg");				// 酒店房间认证结果码   success   error
            marqueeText = jsonObject.getString("ad_text");		        // 跑马灯文本信息


            // 设备认证成功
            if(!TextUtils.isEmpty(authFlag) && authFlag.equals("success")){
                AppContext.getInstance().deviceAuthFlag = true;				// 设备授权成功
            }
            // 直播视频
//            initMediaPlayer();
            // 刷新广告图片
            if(!TextUtils.isEmpty(advUrl)){
//                new AdvDownloadTask(HomeActivity.this, advImageView).execute(new String[]{advUrl});
                //loadBitmap(advImageView, advUrl);
            }
            // 刷新跑马灯消息
            if(TextUtils.isEmpty(marqueeText)){
                marqueeText = "暂无提示信息";
            }

            if(!oldMarqueeText.equals(marqueeText)){
                marqueeTextView.setText(marqueeText);
                oldMarqueeText = marqueeText;
            }

        } catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取视频播放地址
     * @return
     */
    public String getIndexVideoPath() {
        XLog.d("indexVideoFile111=productInfo: " + productInfo);
        if(productInfo == null || productInfo.equals("")) {  //再获取一次厂家信息
            productInfo = XUtils.getSystemInfo();
        }

        XLog.d("indexVideoFile222=productInfo: " + productInfo);
        if(productInfo.equals("MBX")) {  //智诺达S805方案
            saveDirPath = "/mnt/sdcard";
        } else if(productInfo.equals("CNCR") || productInfo.equals("JIUZHOU") || productInfo.equals("Skyworth")) { //九州和初灵方案
            saveDirPath = "/data/local";
        }
        else {  //默认方案
            saveDirPath = "/data/local";
        }

        XLog.d("indexVideoFile333=saveDirPath: " + saveDirPath);
        String tempFilePath = saveDirPath + "/indexVideo";
        String tempFileName = "indexVideo.mp4";
        File file = new File(tempFilePath,tempFileName);
        if(!file.exists() || file.length() == 0) {
            indexVideoFile = indexVideoUrl;
        } else {
            indexVideoFile = saveDirPath + "/indexVideo/indexVideo.mp4";
        }
        XLog.d("indexVideoFile444====: " + indexVideoFile);
        return indexVideoFile;
    }

    /**
     * 初始化首页portal数据
     */
    private void initPortalData(){
        List<BaseView> tmpViews = new ArrayList<>();
        try{
            String portalText = loadPortalDataFormLocal();
            if(!TextUtils.isEmpty(portalText)){
                JSONObject jsonObject = JSON.parseObject(portalText);
                this.id = jsonObject.getInteger("id");
                this.name = jsonObject.getString("name");
                this.backgroud = jsonObject.getString("backgroud");
                this.portalVersion = jsonObject.getString("version");
                JSONArray jsonArray = jsonObject.getJSONArray("views");
                int len = jsonArray.size();
                for(int i = 0; i < len; i++){
                    JSONObject item = jsonArray.getJSONObject(i);
                    BaseView baseView = ComponentFacotry.createView(this, item);
                    tmpViews.add(baseView);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        if(tmpViews.isEmpty()){
            tmpViews = initPortalDefaultView();
        }
        // 刷新绘制界面
        Message message = new Message();
        message.what = MSG_INIT_PORTAL_DATA_VIEW;
        message.obj = tmpViews;
        handler.sendMessage(message);

        // 刷新一次服务器端数据
        loadPortalDataFormServer();
    }

    /**
     * 更新portal数据
     */
    private void updatePortalData(){
        try{
            String portalText = loadPortalDataFormLocal();
            if(TextUtils.isEmpty(portalText)){
                return;
            }
            XLog.i("this.portalVersion, this.portalVersion: " + this.portalVersion);
            JSONObject jsonObject = JSON.parseObject(portalText);
            String version = jsonObject.getString("version");
            XLog.i("String version, String version: " + version);
            // portal数据是否发生变化
            if(TextUtils.equals(version, this.portalVersion)){
                return;
            }
            List<BaseView> tmpViews = new ArrayList<>();
            // 变化了刷新一次数据
            this.id = jsonObject.getInteger("id");
            this.name = jsonObject.getString("name");
            this.backgroud = jsonObject.getString("backgroud");
            this.portalVersion = jsonObject.getString("version");
            JSONArray jsonArray = jsonObject.getJSONArray("views");
            int len = jsonArray.size();
            for(int i = 0; i < len; i++){
                JSONObject item = jsonArray.getJSONObject(i);
                BaseView baseView = ComponentFacotry.createView(this, item);
                tmpViews.add(baseView);
            }
            // 刷新绘制界面
            Message message = new Message();
            message.what = MSG_UPDATE_PORTAL_DATA_VIEW;
            message.obj = tmpViews;
            handler.sendMessage(message);
        } catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 读取默认portal数据
     * @return
     */
    private List<BaseView> initPortalDefaultView() {
        this.id = 0;
        this.name = "系统内置portal";
        this.backgroud = "";
        this.portalVersion = "";
        return DefaultDataService.findDefaultViews(this);
    }

    /**
     * 读取缓存数据
     * @return
     */
    private String loadPortalDataFormLocal(){
        // 初始化数据
        MMKV mmkv = MMKV.defaultMMKV();
        String portalText = mmkv.decodeString(KEY);
        return portalText;
    }

    /**
     * 设置缓存数据
     * @param portalDataText
     */
    private void setPortalDataFormLocal(String portalDataText){
        MMKV mmkv = MMKV.defaultMMKV();
        boolean isOk = mmkv.encode(KEY, portalDataText);
        XLog.i("set portal data, result: " + isOk);
    }

    /**
     * 绘制界面数据
     * @param views
     */
    private void initPortalView(List<BaseView> views){
        // 刷新背景图片
        if(TextUtils.isEmpty(backgroud)){
            rootLayout.setBackgroundResource(R.drawable.bj01);
        } else {
            SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                    rootLayout.setBackground(resource);
                }
            };
            Glide.with(this).load(backgroud).into(simpleTarget);
        }
        // 刷新界面元素
        relasePortalView();
        this.views = views;
        BaseView focusView = null;
        for(BaseView view : views){
            try{
                view.onCreate(rootLayout, rootLayout2);
                if(focusView == null && view.isFocusable()){
                    focusView = view;
                }
            } catch(Exception e){
                e.printStackTrace();
            }
        }
        final BaseView tmpFocusView = focusView;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(tmpFocusView != null){
                    tmpFocusView.requestFocus();
                }
            }
        }, 300);
    }

    /**
     * 释放界面元素
     */
    private void relasePortalView(){
        if(views == null || views.isEmpty()){
            return;
        }
        rootLayout.removeAllViews();
        for(BaseView view : views){
            view.onDestroy();
        }
        views = null;
    }

    // 从服务器端加载最新的portal数据
    private void loadPortalDataFormServer(){
        String tempPortalUrl = portalUrl;
        if(TextUtils.isEmpty(tempPortalUrl)) {
            tempPortalUrl = AppConfig.PORTAL_URL;
        }

        XLog.i("loadPortalDataFormServer---tempPortalUrl: " + tempPortalUrl);
        HttpUtils httpUtils = XHttpProxy.getHttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, tempPortalUrl, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException e, String msg) {
                XToast.makeText(HomeActivity.this, "界面数据加载失败，请检查网络连接！").show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                XLog.i("loadPortalDataFormServer---responseInfo.result: " + responseInfo.result);
                // 更新数据到本地
                setPortalDataFormLocal(responseInfo.result);
                // 更新界面数据
                updatePortalData();
            }
        });
    }

    private enum RoomInitStatus{
        // 未加载   加载中   已经加载成功
        UNDO, LOADING, DONE
    }


    private void getHotspotConfig(String dirName, String FileName) {
        String fileContent = "";
        fileContent = UtilFile.readFile(dirName,FileName);
        if (fileContent.equals("")) {
            XLog.d("dyh---:","getHotspotConfig---> no config");
        } else {
            String[] result = fileContent.split(";");
            Hotname = result[0];
            Hotpassword = result[1];
            auto_openFlag = result[2];
            getConfigFlag = true;
        }
    }

    Thread HotspotConfig = new Thread(new Runnable(){

        @Override
        public void run() {
            // TODO 自动生成的方法存根
            System.out.println("dyh-----auto_openFlag--auto_openFlag = "+auto_openFlag);
            if(auto_openFlag.equals("true")) {
                int tempType = 1; //需要密码
                if(Hotpassword.equals("")) {
                    tempType = 0; //不需要密码
                }

                HotStatus = "on";
                wifiHotUtil.startWifiAp(Hotname,Hotpassword,tempType);
            } else {
                HotStatus = "off";
                wifiHotUtil.closeWifiAp();
            }
        }

    });

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放界面元素
        relasePortalView();
        // 注销广播
        if(networkReceiver != null){
            unregisterReceiver(networkReceiver);
        }
    }
}